login = function (flag) {
    let account = document.getElementById("floatingAccount").value;
    let password = document.getElementById("floatingLoginPassword").value;
    if (account === '') {
        Qmsg.error('账号不能为空')
        return;
    }
    if (!isPhoneNumber(account) && !isEmail(account)) {
        Qmsg.error('账号格式错误！')
        return;
    }
    if (password === '') {
        Qmsg.error("请输入密码！")
    } else if (password.length < 8) {
        Qmsg.error("密码长度不能小于8！")
    } else {
        let loginBtn = document.getElementById('loginBtn');
        let loginLoading = document.getElementById('loginLoading');
        loginLoading.hidden = false
        loginBtn.disabled = true

        axios({
                method: 'post',
                url: '/api/login',
                params: {
                    account: account,
                    password: password
                }
            }
        ).then(function (response) {
            if (response.data.code === 200) {
                let now = new Date();
                now.setMonth(now.getMonth() + 1);
                document.cookie = "token=" + response.data.data + ";path=/;expires=" + now.toUTCString() + ";"
                Qmsg.success("登录成功")
                if (flag) {
                    window.location.href = '/profile'
                } else {
                    window.location.reload()
                }
            } else {
                Qmsg.error(response.data.msg)
            }
            loginBtn.disabled = false
            loginLoading.hidden = true
        }).catch(function (error) {
            console.log(error);
            Qmsg.error("未知错误")
            loginBtn.disabled = false
            loginLoading.hidden = true
        });
    }
}
perfect = function (perfectType) {
    let token = getToken();
    if (token !== undefined) {
        let perfectTitle
        if (perfectType === 0) {
            perfectTitle = document.getElementById('perfect-title').value;
        } else {
            perfectTitle = document.getElementById('perfect-title').innerText;
        }
        let perfectContent = document.getElementById('perfect-content').value;
        if (perfectContent == null || perfectContent === '') {
            Qmsg.warning('内容不能为空')
            return
        }

        if (perfectTitle == null || perfectTitle === '') {
            Qmsg.warning('标题不能为空')
            return
        }
        axios({
            url: '/api/perfect',
            method: 'post',
            data: {
                perfectTitle: perfectTitle,
                perfectContent: perfectContent,
                perfectType: perfectType
            },
            headers: {'Authorization': getToken()}
        }).then(function (response) {
            if (response.data.code === 200) {
                Qmsg.success("提交成功")
            } else {
                if ((response.data.code === 403||response.data.code === 401)){
                    clearToken()
                }
                Qmsg.error(response.data.msg)
            }
        }).catch(function (error) {
            console.log(error);
            Qmsg.error("未知错误")
        });
        if (perfectType !== 0) {
            perfectModel.hide()
        } else {
            document.getElementById('perfect-title').value = ''
        }
        document.getElementById('perfect-content').value = ''
    }else {
        Qmsg.warning('未登录')
        showLoginModel()
    }
}
registerAccount = function () {
    let phone = document.getElementById("floatingPhone").value;
    let password = document.getElementById("floatingRegisterPassword").value;
    let rePassword = document.getElementById("floatingRePassword").value;
    if (phone === '') {
        Qmsg.error('手机号不能为空')
        return;
    }
    if (!isPhoneNumber(phone)) {
        Qmsg.error('手机号格式错误！')
        return;
    }
    if (password === '') {
        Qmsg.error("请输入密码！")
    } else if (password.length < 8) {
        Qmsg.error("密码长度不能小于8！")
    } else if (rePassword !== password) {
        Qmsg.error("两次密码不一致")
    } else {

        axios({
                method: 'post',
                url: '/api/register',
                params: {
                    phone: phone,
                    password: password
                }
            }
        ).then(function (response) {
            if (response.data.code === 200) {
                Qmsg.success("注册成功，请去登录吧")
                document.getElementById("floatingPhone").value = '';
                document.getElementById("floatingRegisterPassword").value = '';
                document.getElementById("floatingRePassword").value = '';
            } else {
                Qmsg.error(response.data.msg)
            }
        }).catch(function (error) {
            console.log(error);
            Qmsg.error("未知错误")
        });
    }
}
var loginModel
var logoutModel

showLoginModel = function () {
    loginModel = new bootstrap.Modal(document.getElementById('loginModal'), {
        //点击背景不关闭
        backdrop: "static",
        //触发键盘esc事件时不关闭
    })
    console.log(loginModel)
    loginModel.show()
}

showLogoutModel = function () {
    //初始化模态框
    logoutModel = new bootstrap.Modal(document.getElementById('logoutModal'))
    logoutModel.show()
}
logout = function () {
    axios.get("/api/web/logout")
        .then(function (response) {
            if (response.data.code === 200) {
                Qmsg.success("退出成功")
                //清楚token
                clearToken()
                window.location.reload()
            } else {
                Qmsg.error(response.data.msg)
            }
            logoutModel.hide()
        }).catch(function (error) {
        console.log(error);
        logoutModel.hide()
        Qmsg.error("未知错误")
    });
}

/**
 * 判断是否是手机号
 * @param tel
 * @returns {boolean}
 */
function isPhoneNumber(tel) {
    const reg = /^0?1[3|4|5|6|7|8][0-9]\d{8}$/;
    return reg.test(tel);
}

/**
 * 判断是否是邮箱
 * @param email
 * @returns {boolean}
 */
function isEmail(email) {
    const reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    return reg.test(email);
}

function getToken() {
    return getCookies('token')
}    //获取cookie方法，封装一个方法getCookies(),传入一个属性参数，可以获取对应的属性值
function clearToken(){
    document.cookie = 'token' + '=0;path=/;expires=' + new Date(0).toUTCString();
}
function getCookies(name) {
    const str = document.cookie;    //获取所有的cookie，得到的是一个字符串
    const arr = str.split("; "); //注意：分号后面有一个空格
    for (let i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split("=")
        if (arr2[0] === name) {
            return arr2[1]
        }
    }
}
